package com.aw.baselib.net.callback

import com.aw.baselib.R
import com.aw.baselib.base.AwBaseApplication
import com.aw.baselib.base.AwResponseBean
import com.aw.baselib.bean.rx.EventReLoginType
import com.aw.baselib.util.AwLog.d
import io.reactivex.functions.Consumer
import org.greenrobot.eventbus.EventBus

/**
 * @author : hzw
 * @date : 2021/12/10
 */
class AwRspSubscriber<T>(private val mRspCallback: AwRspCallback<T>?) :
    Consumer<AwResponseBean<T>?> {
    override fun accept(rspBean: AwResponseBean<T>?) {
        if (null == mRspCallback) {
            d("===AwRspConsumer callback is null, return")
        } else {
            if (rspBean == null) {
                d("===AwRspConsumer callback rspBean is null")
                mRspCallback.onFailure(UNKNOWN_CODE,
                    AwBaseApplication.instance?.getString(R.string.common_server_return_empty_data)
                )
            } else {
                d("===AwRspConsumer callback rspBean is normal, rspBean: $rspBean")
                if (rspBean.isTokenError) {
                    EventBus.getDefault().postSticky(EventReLoginType(null))
                } else if (rspBean.isSuccess) {
                    rspBean.data?.let { mRspCallback.onSuccess(it) }
                } else {
                    mRspCallback.onFailure(rspBean.code, rspBean.msg)
                }
            }
            mRspCallback.onCompleted()
        }
    }

    companion object {
        const val UNKNOWN_CODE = -1
    }
}